import React from 'react'
import GameAIModel from "../../../model/GameAIModel";
import {formatDate, formatScheduleDate} from "../../../utils/dateService";
import DefaultTeamIcon from "../../../res/images/web/shared/缺省头像.png";
import {ICON_URL_PREFIX} from "../../../redux/game";
import {bindEvent, getDom, getDoms} from "../../../utils/commonfunc";
import _ from "lodash";
import {withRouter} from 'react-router-dom'

class RecentAiList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            currentDate: '',
        }
    }

    componentDidMount() {
        this.bindScrollEvent()
    }

    toDateObject = (list) => {

        let result = {}
        list.map(val => {
            const model = new GameAIModel(val)
            const detail = model.detail()
            const schedule = detail.schedule
            const scheduleTimeObj = new Date(schedule * 1000)
            const scheduleDateString = formatDate(scheduleTimeObj)
            let scheduleDateKey = scheduleDateString.slice(0, 4) + '年' + scheduleDateString.slice(4, 6) + '月' + scheduleDateString.slice(6) + '日'
            const valArr = result[scheduleDateKey]
            if (valArr) {
                result[scheduleDateKey].push(model)
            } else {
                result[scheduleDateKey] = [model]
            }
        })


        return result

    }

    bindScrollEvent = () => {
        // const ctn = getDom('.am-tabs-pane-wrap-active')
        // const ctns = getDoms('.am-tabs-pane-wrap')

        // const ctn = ctns[this.props.style - 1]
        const ctn = this.ctn

        // console.log(ctns)
        // const top = ctn.scrollTop
        //
        // const ScrollHei = ctn.scrollHeight
        // const clientHei = ctn.clientHeight
        // const gap = ScrollHei - top - clientHei
        const scrollCallback = _.debounce(() => {

            const top = ctn.scrollTop
            const scrollHei = ctn.scrollHeight
            const hei = document.documentElement.clientHeight - 45

            if (top + hei === scrollHei) {
                this.props.getNext()
            }
            // const items = getDoms('.am-tabs-pane-wrap-active .AI-result-ctn-large')
            // const dateSpans = getDoms('.recent-ai-date-span')
            // for (let i = 0; i < dateSpans.length; i++) {
            //     let span = dateSpans[i]
            //     const rect = span.getBoundingClientRect()
            //     const y = rect.y
            //     if (y > 88.5 && y < 200) {
            //         span.classList.add('recent-ai-date-span-fixed')
            //     } else {
            //         if (y !== 88.5) {
            //             span.classList.remove('recent-ai-date-span-fixed')
            //         }
            //
            //
            //     }
            //
            // }
            //
            // const lastItem = items[items.length - 1]
            // const rect = lastItem.getBoundingClientRect()
            // const hei = document.documentElement.clientHeight
            // const y = rect.y
            // if (y < hei) {
            //     this.props.getNext(this.props.style)
            // }
            // const content = this.ctnContent
            // const contentHeight = content.scrollHeight
            // const afterScrollHeight = document.documentElement.clientHeight - 64 - 43.5
            // const top = ctn.scrollTop
            // if (top > 0 && afterScrollHeight < contentHeight) {
            //     this.props.setAtTop(false)
            // } else if (top === 0) {
            //     this.props.setAtTop(true)
            // }
        }, 100)
        if (ctn) {
            bindEvent(ctn, 'scroll', scrollCallback)
        }
    }

    render() {
        const list = this.props.list
        const dateObj = this.toDateObject(list)

        const listTemplate = Object.keys(dateObj).map((date, index) => {
            const dateSpan = <div
                style={{
                    height: '24px',
                    width: '100%',
                    top: 0,
                    background: '#EAEAEA',
                    textAlign: 'center',
                    position: 'sticky',
                    WebkitPosition: 'sticky',
                    // position: 'fixed',
                    // top: 88.5,
                    // left: 0,
                    zIndex: 2,
                }}
                // className='recent-ai-date-span'
                className={'recent-ai-date-span'}
                // className={index === 0
                //     ? 'recent-ai-date-span recent-ai-date-span-fixed'
                //     : 'recent-ai-date-span'
                // }
            >
                <span
                    style={{
                        lineHeight: '24px',
                    }}
                >
                    {date}
                </span>
            </div>
            const list = dateObj[date].map((model, index) => {
                const detail = model.detail()

                const schedule = detail.schedule
                const startAt = detail.startAt
                const homeTeam = detail.host
                const awayTeam = detail.away
                const scheduleTimeObj = new Date(schedule * 1000)
                const scheduleDateString = formatDate(scheduleTimeObj)
                const scheduleTimeString = formatScheduleDate(scheduleTimeObj)
                let scheduleDateFormat = scheduleDateString.slice(4, 6) + '月' + scheduleDateString.slice(6) + '日'
                const scheduleDiv = (<div className='my-ai-card-time-not-started'>
                    <span>{scheduleDateFormat} {scheduleTimeString}</span>
                </div>)

                const teamStyle = {
                    flex: 1,
                    fontSize: '12px',
                    fontWeight: 600,
                    color: 'rgba(51,51,51,1)',
                    lineHeight: '16px',
                    textAlign: 'center',
                }

                const teamIcon = (team, home = true) => {
                    // const {
                    //     detail,
                    // } = team
                    const {
                        name,
                        logo,
                    } = team

                    const nameSpan = <span style={{textAlign: home ? 'right' : 'left',}}>{name}</span>

                    return <div
                        className='AI-game-card-team-logo'
                        style={{
                            justifyContent: home ? 'flex-end' : 'flex-start',
                        }}
                    >
                        {home ? nameSpan : null}
                        <img
                            src={logo === '' ? DefaultTeamIcon : ICON_URL_PREFIX + logo}
                            alt=''
                        />
                        {home ? null : nameSpan}
                    </div>
                }

                const c = <span className='my-ai-card-c'>
                {detail.c}
            </span>
                const homeScore = homeTeam.score
                const awayScore = awayTeam.score
                const score = <div className='AI-game-card-team-VS'>
                    <span>{homeScore} : {awayScore}</span>
                </div>

                let odds
                // let style = this.state.style
                let style = detail.showStyleType

                let RQ = model.RQ()
                let SFP = model.SFP()
                let DXQ = model.DXQ()

                let dataM = {
                    1: {
                        data: RQ,
                    },
                    2: {
                        data: SFP,
                    },
                    3: {
                        data: DXQ,
                    },
                }


                let oddsData = dataM[style].data
                let result = oddsData.result
                let title = oddsData.title
                let subTitle = oddsData.subTitle
                let resultRate = oddsData.resultRate

                let textM = {
                    1: {
                        text: `${title}${subTitle? `-${subTitle}` : ''}：${resultRate}%`
                    },
                    2: {
                        text: `首选：${SFP.first}% 次选：${SFP.second}%`
                    },
                    3: {
                        text: `${title}-${subTitle}：${resultRate}%`,
                    }
                }


                let resultTextMapper = {
                    1: '准',
                    2: '错',
                    3: '走',
                }
                let bgMapper = {
                    1: '#FA7268',
                    3: '#FFA500',
                    2: '#BEBEBE',
                }

                const oddsCtn = {
                    height: '28px',
                    width: '100%',
                    backgroundColor: bgMapper[result],
                    padding: '6px 12px',
                }

                const spanStyle = {
                    color: '#fff',
                }

                let oddsTemplate = <div
                    style={oddsCtn}
                    className='flex-space-between-align-center'
                >
                    <span style={spanStyle}>
                        {textM[style].text}
                    </span>
                        <span style={spanStyle}>
                        {resultTextMapper[result]}
                    </span>
                </div>



                return <div
                    key={index}
                    className='AI-result-ctn-large'
                    onClick={() => this.props.history.push(`../game/${detail.matchId}`)}
                >
                    {c}
                    {scheduleDiv}
                    {teamIcon(homeTeam)}
                    {score}
                    {teamIcon(awayTeam, false)}
                    {oddsTemplate}
                </div>
            })
            return <div
                key={date}
            >
                {dateSpan}
                {list}
            </div>
        })


        return <div
            ref={el => this.ctn = el}
            style={{
                height: 'calc(100 * var(--vh) - 45px)',
                overflowY: 'scroll'
            }}
        >
            {listTemplate}
        </div>
    }
}

export default withRouter(RecentAiList)
